define(['./../initial', './../service/showMsg', './PrjStatus', './Project.Extend.ChordStastic', './Project.Extend.MonitorPoints'], function () {
    var app = angular.module('App.home');
    app.factory('Project', ['$q', '$http', 'showMsg', 'PrjStatus', '$rootScope', 'Project.Extend.ChordStastic', 'Project.Extend.MonitorPoints',
        function ($q, $http, showMsg, PrjStatus, $rootScope, ProjectChordExtend, ProjectMonitorPointsExtend) {
            var Project = function () {
                this.center = null;
                this.monitorTypes = [];
                this.monitorPointsDictionary = [];
                this.bindProjectList = [];
            };

            Project.allMonitorTypes = [];
            Project.allAutoSurveyStations = [];
            Project.cityList = [];
            Project.filterPrjTypes = [];//所有工程的code和type集合
            Project.mix = function (obj) {
                for (var key in obj) {
                    if (Project.prototype.hasOwnProperty(key)) {
                        throw new Error('不能覆盖已有的原型方法' + key);
                    }
                    Project.prototype[key] = obj[key];
                }
            };
            //------------------------------静态方法-------------------------------------

            //获取所有的有权限项目,以city->lines->projects的结构,获取结果是city array
            //具体结构参考Web/models下的定义
            Project.getAllCityList = function (typeCode) {
                var defer = $q.defer();
                if (Project.cityList.length > 0 && !typeCode) {
                    defer.resolve(Project.cityList);
                } else {
                    $http({
                        method: 'get',
                        url: typeCode ? '/project/type/' + typeCode : '/project/type',
                    }).success(function (data) {
                        if (data) {
                            if (!typeCode) {
                                Project.cityList = data.cityList;
                            }
                            if (Project.filterPrjTypes.length === 0) {
                                Project.filterPrjTypes = data.filterPrjTypes;
                            }
                            defer.resolve(data.cityList);
                        } else {
                            showMsg('获取工程列表失败!', 'alert');
                            defer.resolve(null);
                        }
                    });
                }
                return defer.promise;
            };
            
            //查找当前的线路
            Project.getCurLine = function (lineId, prjList) {
                lineId = lineId - 0;
                var allProjects = prjList || Project.cityList;
                for (var i = 0; i < allProjects.length; i++) {
                    for (var j = 0; j < allProjects[i].lines.length; j++) {
                        //查找到匹配项
                        if (allProjects[i].lines[j].lineId === lineId) {
                            for (var k = 0; k < allProjects[i].lines[j].projects.length; k++) {
                                var item = allProjects[i].lines[j].projects[k];
                                if (item.constructor !== Project) {
                                    var prj = new Project();
                                    //让item继承Project
                                    allProjects[i].lines[j].projects[k] = angular.extend(prj, item);
                                }
                            }
                            return allProjects[i].lines[j];
                        }
                    }
                }
                return null;
            };

            //查找到当前的项目
            Project.getCurProject = function (prjId, prjList) {
                prjId = prjId - 0;
                var allProjects = prjList || Project.cityList;
                for (var i = 0; i < allProjects.length; i++) {
                    for (var j = 0; j < allProjects[i].lines.length; j++) {
                        for (var k = 0; k < allProjects[i].lines[j].projects.length; k++) {
                            var item = allProjects[i].lines[j].projects[k];
                            if (item.prjId === parseInt(prjId, 0)) {
                                if (item.constructor !== Project) {
                                    var prj = new Project();
                                    //让item继承Project
                                    item = angular.extend(prj, item);
                                    // allProjects[i].lines[j].projects[k] = item;
                                }
                                $rootScope.curPrj = item;
                                return item;
                            }
                        }
                    }
                }
                return null;
            };

            //获取当前能设置的所有监测项
            Project.getAllMonitorTypes = function () {
                var defer = $q.defer();
                if (Project.allMonitorTypes > 0) {
                    defer.resolve(Project.allMonitorTypes);
                } else {
                    $http({
                        method: 'get',
                        url: '/project/allMonitorTypes'
                    }).success(function (data) {
                        Project.allMonitorTypes = data;
                        defer.resolve(Project.allMonitorTypes);
                    });
                }
                return defer.promise;
            };

            //获取自动化设备
            Project.getAllAutoSurveyStations = function (prj) {
                var defer = $q.defer();
                if (Project.allAutoSurveyStations > 0) {
                    prj.bindAutoSurveyStations(Project.allAutoSurveyStations);
                    defer.resolve(Project.allAutoSurveyStations);
                } else {
                    $http({
                        method: 'get',
                        url: '/project/allAutoSurveyStations'
                    }).success(function (data) {
                        Project.allAutoSurveyStations = data;
                        prj.bindAutoSurveyStations(Project.allAutoSurveyStations);
                        defer.resolve(Project.allAutoSurveyStations);
                    });
                }
                return defer.promise;
            };



            // 添加一个项目
            Project.addProject = function (obj) {
                var defer = $q.defer();
                $http({
                    method: 'post',
                    url: '/project/addnew',
                    data: obj
                }).success(function (data) {
                    //删除现有列表
                    Project.cityList.length = 0;
                    defer.resolve(data);
                }).error(function () {
                    defer.reject();
                });
                return defer.promise;
            };

            //end------------------------------静态方法-------------------------------------

            //---------------------------------------类方法----------------------------------
            Project.prototype._requestHelper = function (method, action, postData) {
                if (!method || !action) return;
                var _this = this;
                var defer = $q.defer();
                action = action.replace(method, '');
                //后台的api约定为/project/{:prjID}/action的模式
                var url = "/project/" + _this.prjId.toString() + "/" + action;
                $http({
                    method: method,
                    url: url,
                    data: postData ? {
                        postData: postData, //约定postData为post的内容
                        prj: _this //约定每次post的时候,把工程自己的数据也post回服务器
                    } : undefined
                }).success(function (data) {
                    if (data.toString() === 'false' && method !== 'get') {
                        showMsg('发生错误,请重试!', 'alert');
                    }
                    defer.resolve(data);
                }).error(function (reason) {
                    defer.reject(reason);
                });
                return defer.promise;
            };

            Project.prototype.delete = function () {
                var prj = this;
                var defer = $q.defer();
                prj._requestHelper('post', 'postDelete', 1).then(function (data) {
                    defer.resolve();
                });
                return defer.promise;
            };

            Project.prototype.postCenter = function () { // 更改项目位置
                var prj = this;
                var defer = $q.defer();
                if (!prj.center) {
                    showMsg('请先在地图上指定项目地址', 'alert');
                    defer.resolve(false);
                } else {
                    var centerJSONStr = JSON.stringify(prj.center);
                    prj._requestHelper('post', 'postCenter', centerJSONStr).then(function (data) {
                        defer.resolve();
                    });
                }
                return defer.promise;
            };
            Project.prototype.getStatusList = function () { // 获取工况列表
                var prj = this;
                var defer = $q.defer();
                if (prj.statusList) {
                    defer.resolve(prj.statusList);
                } else {
                    prj
                        ._requestHelper('get', 'getStatusList')
                        .then(function (data) {
                            if (data.length > 0) {
                                data.forEach(function (item) {
                                    var st = new PrjStatus();
                                    item = angular.extend(st, item);
                                });
                            }
                            prj.statusList = data;
                            prj._parseStatusToMainStatus();//复制成主工况
                            defer.resolve(prj.statusList);
                        });
                }
                return defer.promise;
            };
            
            /*把工况列表渲染成主工况,即Title一致的合并*/
            Project.prototype._parseStatusToMainStatus = function () {
                var _this = this;
                if (!_this.statusList || _this.statusList.length === 0) return;
                var status = "";
                _this.mainStatusTimeList = [];
                for (var index = 0; index < _this.statusList.length; index++) {
                    var item = _this.statusList[index];
                    if (item.Title !== status) {
                        status = item.Title;
                        _this.mainStatusTimeList.push({
                            status: status,
                            date: Date.parse(item.Date)
                        });
                    }
                }
            };

            Project.prototype.postStatus = function (status) { // 上传工况
                var prj = this;
                var defer = $q.defer();
                status.BindPrjIdList = prj.bindProjectList.length > 0 ? prj.bindProjectList.map(function (item) {
                    return item.PrjId;
                }) : [];
                prj
                    ._requestHelper('post', 'postStatus', status)
                    .then(function (data) {
                        if (data.toString() === 'true') {
                            showMsg('上传工况成功！', 'info');
                            defer.resolve(true);
                        } else {
                            showMsg('发生错误！', 'alert');
                            defer.resolve(false);
                        }
                    });
                return defer.promise;
            };
            Project.prototype.deleteStatus = function (dateList) { // 删除工况
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('delete', 'deleteStatus/' + JSON.stringify(dateList))
                    .then(function () {
                        showMsg('成功删除工况！', 'info');
                        defer.resolve(dateList);
                    });
                return defer.promise;
            };
            Project.prototype.postSummary = function () { // 提交工程概况
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('post', 'postSummary', prj)
                    .then(function (data) {
                        if (data) {
                            defer.resolve();
                        } else {
                            defer.reject();
                        }
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.getMonitorTypes = function () { // 获取监测类型
                var prj = this;
                var defer = $q.defer();
                if (prj.monitorTypes.length > 0) {
                    defer.resolve(prj.monitorTypes);
                } else {
                    prj
                        ._requestHelper('get', 'getMonitorTypes')
                        .then(function (data) {
                            defer.resolve(data);
                        }, function () {
                            defer.reject();
                        });
                }
                return defer.promise;
            };
            Project.prototype.postMonitorTypes = function (types) { // 更新监测类型
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('post', 'postMonitorTypes', {
                        prjId: prj.prjId,
                        monitorTypes: types,
                        autoSurveyList: types.indexOf('自动化收敛') > -1 ? Project.allAutoSurveyStations : null
                    })
                    .then(function () {
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.bindAutoSurveyStations = function (list) { // 绑定自动化设备
                var prj = this;
                list.forEach(function (item) {
                    if (item.prjid === prj.prjId) {
                        item.bind = true;
                    } else {
                        item.bind = false;
                    }
                });
            };
            Project.prototype.getMonitorPointsDictionary = function () { // 获取监测点
                var prj = this;
                var defer = $q.defer();
                if (prj.monitorPointsDictionary.length > 0) {
                    defer.resolve(prj.monitorPointsDictionary);
                } else {
                    prj
                        ._requestHelper('get', 'getMonitorPointsDictionary')
                        .then(function (data) {
                            defer.resolve(prj.monitorPointsDictionary = data);
                        }, function () {
                            defer.reject();
                        });
                }
                return defer.promise;
            };
            Project.prototype.deletePoints = function (option) {
                var prj = this;
                var defer = $q.defer();
                var url = option.monitorType ? ('deletePoints/' + encodeURIComponent(option.date) + "/" + encodeURIComponent(option.monitorType) + "/" + encodeURIComponent(option.location)) : ('deletePoints/' + encodeURIComponent(option.date));
                prj
                    ._requestHelper('delete', url)
                    .then(function () {
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.postMonitorPointsDictionary = function (data) { // 更新监测点（手动输入）
                var prj = this;
                var defer = $q.defer();
                prj.monitorPointsDictionary = data;
                prj
                    ._requestHelper('post', 'postMonitorPointsDictionary', {
                        prjId: prj.prjId,
                        dict: data
                    })
                    .then(function () {
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.postMonitorPointsConfig = function (data) { // 更新监测点（Excel上传）
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('post', 'postMonitorPointsConfig', data)
                    .then(function () {
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.getMileage = function () { // 获取里程环号
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('get', 'getMileage')
                    .then(function () {
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.postMileage = function (data) { // 更新里程环号
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('post', 'postMileage', data)
                    .then(function () {
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.getBindProject = function () { // 获取已绑定工程
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('get', 'getBindProject')
                    .then(function (data) {
                        prj.bindProjectList = data;
                    });
                return defer.promise;
            };
            Project.prototype.postBindProject = function (prjName) { // 绑定新工程
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('post', 'postBindProject', {
                        prjId: prj.prjId,
                        prjName: prjName
                    })
                    .then(function () {
                        prj.getBindProject();
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.deleteBindProject = function (prjName) { // 删除已绑定工程
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('delete', 'deleteBindProject/' + prjName)
                    .then(function () {
                        prj.getBindProject();
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.postProperties = function () { // 更新属性
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('post', 'postProperties', true)
                    .then(function () {
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.getLayers = function () { // 检测布点图是否存在，并不返回实际内容
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('get', 'getLayers')
                    .then(function (data) {
                        try {
                            var layers = JSON.parse(data);
                            if (Array.isArray(layers) && layers.length != 0)
                                defer.resolve();
                            else
                                defer.reject();
                        } catch (error) {
                            defer.reject(error);
                        }
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };
            Project.prototype.postLayers = function (layers) { // 上传布点图
                var prj = this;
                var defer = $q.defer();
                prj
                    ._requestHelper('post', 'postLayers', layers)
                    .then(function () {
                        defer.resolve();
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };

            Project.prototype.getReviewChange = function (monitorType, location, date) {
                var prj = this;
                var defer = $q.defer();
                var action = "getReviewChange/" + encodeURIComponent(monitorType) + '/' + encodeURIComponent(location) + '/' + encodeURIComponent(date);
                prj
                    ._requestHelper('get', action)
                    .then(function (data) {
                        defer.resolve(data);
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };

            Project.prototype.postReviewProject = function (paras) {
                var prj = this;
                var defer = $q.defer();
                var action = "postReviewProject";
                prj
                    ._requestHelper('post', action, paras)
                    .then(function (data) {
                        defer.resolve(data);
                    }, function () {
                        defer.reject();
                    });
                return defer.promise;
            };

            //扩展方法
            Project.mix(ProjectChordExtend);
            Project.mix(ProjectMonitorPointsExtend);
            return Project;
        }
    ]);
});
